import os
from datetime import datetime

from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.utils.decorators import method_decorator
from django.views import View

from Record_project.settings import MEDIA_ROOT
from fun.forms import RecordForms, UserForms
from fun.models import *
from users.forms import UserForm


# Create your views here.

def main(requests, **kwargs):
    username = requests.user.username
    records = Records.objects.all()
    return render(requests, 'function/all_record.html',
                  context={
                      'classify': Classify.objects.all(),
                      'username': username,
                      'records': records,
                  })


def main_page(requests, **kwargs):
    username = requests.user.username
    new_classes = kwargs.get('classify')
    try:
        res = Classify.objects.get(name=new_classes)
    except Classify.DoesNotExist:
        return redirect('not_found')
    return HttpResponse(render(requests, 'function/main.html',
                               context={
                                   'classify': Classify.objects.all(),
                                   'username': username,
                                   'new_class': new_classes,
                                   'records': res.records_set.all(),
                               }))


def not_found(request, **kwargs):
    return HttpResponse("<h1>很抱歉，暂时没有相关内容*_*</h1>")


def homepage(request, **kwargs):
    return HttpResponse(render(request, 'users/homepage.html',
                               context={
                                   'classify': Classify.objects.all(),
                                   'username': request.user.username,
                               }
                               ))


class PublishView(View):
    @method_decorator(login_required)
    def get(self, request):
        form = RecordForms()
        username = request.user.username
        return render(request, 'function/publish.html',
                      {'username': username, 'form': form},
                      )

    def post(self, request):
        form = RecordForms(request.POST, request.FILES)
        username = request.user.username
        if form.is_valid():
            print("通过校验")
            title = form.cleaned_data.get('title')
            content = form.cleaned_data.get('content')
            classify = form.cleaned_data.get('classify')
            description = form.cleaned_data.get('description')
            picture = form.cleaned_data.get('picture')
            user = request.user
            labels = form.cleaned_data.get('label')
            file_name = f'{datetime.now().strftime("%Y%m%d%H%M%S")}_{picture.name}'
            with open(os.path.join(MEDIA_ROOT, file_name), 'wb') as fp:
                for data in picture.chunks():
                    fp.write(data)
            record = Records.objects.create(title=title, content=content, classify=classify, description=description,
                                            picture=file_name, user=user)
            for i in labels:
                record.label.add(i)
        else:
            print("校验失败")
        return render(request, 'function/publish.html', {'username': username, 'form': form})


class RecordDetailView(View):
    def get(self, request, id):
        user = Records.objects.get(id=id)
        user_id = user.user_id
        try:
            record = Records.objects.get(id=id)
        except Records.DoesNotExist:
            return redirect('not_found')
        return render(request, 'function/record_detail.html',
                      context={
                          'record': record,
                          'username': request.user.username,
                          'labels': record.label.all(),
                          'user_id': user_id,
                      })


class RecordUser(View):
    @method_decorator(login_required)
    def get(self, request):
        record = Records.objects.filter(user=request.user)
        return render(request, 'users/user_centre.html',
                      {'username': request.user.username,
                       'records': record,
                       })


class RecordUpdate(View):
    @method_decorator(login_required)
    def get(self, request, id):
        try:
            record = Records.objects.get(id=id)
        except Records.DoesNotExist:
            return redirect('not_find')
        data = {
            'title': record.title,
            'description': record.description,
            'content': record.content,
            'picture': record.picture,
            'classify': record.classify,
            'label': record.label.all()
        }
        form = RecordForms(data)
        return render(request, 'users/user_records.html',
                      {'username': request.user.username,
                       'form': form,
                       })

    def post(self, request, id):
        form = RecordForms(request.POST, request.FILES)
        if form.is_valid():
            print("通过校验")
            title = form.cleaned_data.get('title')
            content = form.cleaned_data.get('content')
            description = form.cleaned_data.get('description')
            picture = form.cleaned_data.get('picture')
            user = request.user
            classify = form.cleaned_data.get('classify')
            labels = form.cleaned_data.get('label')
            file_name = f'{datetime.now().strftime("%Y%m%d%H%M%S")}_{picture.name}'
            with open(os.path.join(MEDIA_ROOT, file_name), 'wb') as fp:
                for data in picture.chunks():
                    fp.write(data)
            record = Records.objects.filter(id=id)
            os.remove(os.path.join(MEDIA_ROOT, record[0].picture))
            records = record.update(title=title, content=content, description=description, picture=file_name,
                                    user=user,
                                    classify=classify)
            record[0].label.clear()
            for i in labels:
                record[0].label.add(i)
        return redirect('RecordUser')


class RecordDelete(View):
    def get(self, request, id):
        try:
            record = Records.objects.get(id=id)
        except Records.DoesNotExist:
            return redirect('not_found')
        os.remove(os.path.join(MEDIA_ROOT, record.picture))
        record.delete()
        return redirect('RecordUser')


class UserView(View):
    @method_decorator(login_required)
    def get(self, request):
        form = UserForms()
        username = request.user.username
        user = User.objects.get(username=username)
        user_id = user.id
        userdetail = UserDetail.objects.filter(user_id=user_id)
        return render(request, 'function/user.html',
                      {'username': username, 'form': form, 'user_id': user_id, 'userdetail': userdetail},
                      )

    def post(self, request):
        form = UserForms(request.POST, request.FILES)
        username = request.user.username
        user = User.objects.get(username=username)
        user_id = user.id
        if form.is_valid():
            print("通过校验")
            nickname = form.cleaned_data.get('nickname')
            age = form.cleaned_data.get('age')
            sex = form.cleaned_data.get('sex')
            birthday = form.cleaned_data.get('birthday')
            QQ = form.cleaned_data.get('QQ')
            id = UserDetail.objects.get(user_id=user_id)
            if id:
                userdetail = UserDetail.objects.update(nickname=nickname, age=age, sex=sex,
                                                       birthday=birthday,
                                                       QQ=QQ)
            else:
                userdetail = UserDetail.objects.create(nickname=nickname, age=age, sex=sex,
                                                       birthday=birthday,
                                                       QQ=QQ, user_id=user_id)
        else:
            print("校验失败")
        return render(request, 'function/user.html', {'username': username, 'form': form})


class UserDetailView(View):
    def get(self, request, id):
        user = UserDetail.objects.get(id=id)
        id = user.user_id
        name = User.objects.get(id=id).username
        username = request.user.username
        try:
            user = UserDetail.objects.get(user_id=id)
        except UserDetail.DoesNotExist:
            return redirect('not_found')
        return render(request, 'function/userdetail.html',
                      context={
                          'user': user,
                          'username': username,
                          'name': name,
                      })
